package logic

import (
	"context"
	"errors"
	"math/rand"
	"strconv"
	"time"
	"video-management-system/cache"
	"video-management-system/pkg"
	"video-management-system/userrpc/internal/svc"
	"video-management-system/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SandLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSandLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SandLogic {
	return &SandLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 短信验证码
func (l *SandLogic) Sand(in *userrpc.SandRequest) (*userrpc.SandResponse, error) {
	// todo: add your logic here and delete this line
	i, _ := cache.Rdb.Get(l.ctx, "smsNumber"+in.Phone).Int()
	if i >= 1 {
		return nil, errors.New("1分钟内仅允许发送1次验证码")
	}
	code := rand.Intn(9000) + 1000
	sand, err := pkg.Sand(in.Phone, strconv.Itoa(code))
	if err != nil {
		return nil, err
	}
	if sand.Code != 2 {
		return nil, errors.New("发送失败")
	}
	cache.Rdb.Set(l.ctx, "sms"+in.Phone, code, time.Minute*5)
	result, _ := cache.Rdb.Incr(l.ctx, "smsNumber"+in.Phone).Result()
	if result == 1 {
		cache.Rdb.Expire(l.ctx, "smsNumber"+in.Phone, time.Minute*1)
	}
	return &userrpc.SandResponse{}, nil
}
